package io;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class IOSender {
	private static final int BUF_SIZE = 256 * 1024 - 1;

	public static void main(String[] args) throws IOException {
		String serverHostname = new String("127.0.0.1"); // "192.168.1.105"

		System.out.println("Attemping to connect to host " + serverHostname
				+ " on port 7777.");

		Socket echoSocket = null;

		long start = System.currentTimeMillis();

		try {

			echoSocket = new Socket(serverHostname, 7777);
			OutputStream socketOut = echoSocket.getOutputStream();
			InputStream socketIn = echoSocket.getInputStream();

			DataInputStream fileIn = new DataInputStream(new FileInputStream(
					new File("data/data.bin")));

			byte[] buf = new byte[BUF_SIZE];
			int size = BUF_SIZE + 1;
			while (size >= BUF_SIZE && size != 0) {
				size = fileIn.read(buf);
				socketOut.write(buf, 0, size);
			}

			System.out.println("Data sent. Waiting for ACK.");
			int ack = socketIn.read();
			if (ack == 77) {
				System.out.println("ACK received. TX verified.");
			}

			socketOut.close();
			socketIn.close();

			fileIn.close();

			long end = System.currentTimeMillis();
			long delta = end - start;
			System.out.println("Total time (net copy): " + delta + " ms.");
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: " + serverHostname);
			System.exit(1);
		} catch (IOException e) {
			System.out.println(e);

			long end = System.currentTimeMillis();
			long delta = end - start;
			System.out.println("Total time (net copy): " + delta + " ms.");

			throw e;
			// System.err.println("Couldn't get I/O for " +
			// "the connection to: "
			// + serverHostname);
			// System.exit(1);
		}

		echoSocket.close();
	}
}